<?php
// 应用公共文件
use \Firebase\JWT\JWT;
use think\exception\HttpResponseException;
use think\Response;

/**
 * info: 生成jwt
 * User: 伍先生
 * Argument:
 * DateTime: 2020/12/7 17:53
 * Url: setJwt
 */
function setJwt($key, $arr = [], $time = 7200)
{
    $payload = $arr;
    /**
     * You can add a leeway to account for when there is a clock skew times between
     * the signing and verifying servers. It is recommended that this leeway should
     * not be bigger than a few minutes.
     *
     * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
     */
    JWT::$leeway = 60;
    /**
     * IMPORTANT:
     * You must specify supported algorithms for your application. See
     * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
     * for a list of spec-compliant algorithms.
     */
    $jwt = JWT::encode($payload, $key);
    return $jwt;
}

/**
 * info: 校验jwt
 * User: 伍先生
 * Argument:
 * DateTime: 2020/12/7 17:53
 * Url: checkJwt
 */
function checkJwt($key, $jwt)
{
    try {
        $decoded = JWT::decode($jwt, $key, array('HS256'));
        return json_encode($decoded, 256);
    }catch (Exception $e){
        return false;
    }

}

/**
 * info: 获取客户端IP
 * User: 伍先生
 * Argument:
 * DateTime: 2020/12/7 17:53
 * Url: get_client_ip
 */
function get_client_ip($type = 0, $adv = true)
{
    return request()->ip($type, $adv);
}

/**
 * info: 设置密码
 * User: 伍先生
 * Argument:
 * DateTime: 2020/12/7 22:18
 * Url: set_password
 */
function set_password($str, $salt = "jwcode")
{
    return md5(base64_decode(md5(crypt($str, $salt))));
}

/**
 * 返回封装后的API数据到客户端
 * @param mixed $data 要返回的数据
 * @param integer $code 返回的code
 * @param mixed $msg 提示信息
 * @param string $type 返回数据格式
 * @param array $header 发送的Header信息
 * @return void
 */
function result($data, $code = 0, $msg = '', $type = 'json', array $header = [])
{
    $result = [
        'code' => $code,
        'msg' => $msg,
        'time' => time(),
        'data' => $data,
    ];
    $header["jw-name"] = "JwCode";
    $header["jw-url"] = "http://jwcode.cn/";
    $response = Response::create($result, $type)->header($header);

    throw new HttpResponseException($response);
}
